package com.swedne.test

import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.PixelFormat
import android.hardware.Camera
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.os.storage.StorageManager
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.swedne.test.common.utils
import com.swedne.test.dataBase.DBEngine
import com.swedne.test.dataBase.Table
import com.swedne.test.dnake.dmsg
import com.swedne.test.dnake.dxml
import com.swedne.test.luatest.LuaTest
import com.swedne.test.notification.MyNotifiService
import com.swedne.test.voice.VoiceControl
import com.swedne.test.weblogs.LogcatRunner
import java.io.IOException
import java.util.concurrent.atomic.AtomicInteger
import java.util.regex.Pattern

class MainActivity : AppCompatActivity() {
    private var tvText: TextView? = null
    private val camera: Camera? = null // Camera对象，相机预览
    private var subHandle: Handler? = null
    private var isAdbOpend = true
    private var dbEngine: DBEngine? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tvText = findViewById(R.id.tv_text)
        dbEngine = DBEngine(this)

        //java 调用lua 脚本
        val luaTest = LuaTest(this)
        luaTest.runLuaScript()
        //lua 调用Android 方法
        luaTest.runLuaCallJava()
        addFloatView()
        val i = AtomicInteger(0)
        Log.i("zzzzzzzzzz", "onCreate=" + resources.configuration.orientation)
        findViewById<View>(R.id.btn_query)?.setOnClickListener { v: View? -> query() }
        findViewById<View>(R.id.btn_insert)?.setOnClickListener { v: View? -> insert() }
        tvText?.setOnClickListener(View.OnClickListener { v: View? ->
            Log.i("zzzzzzzzzz", "send message=")
            val dmsg = dmsg()
            val dxml = dxml()
            dxml.setText("/params/cmd", "reboot")
            dmsg.to("/upgrade/root/cmd", dxml.toString())
        })
        findViewById<View>(R.id.tv_voice)?.setOnClickListener { v: View? ->
            startActivity(
                Intent(
                    this@MainActivity,
                    VoiceControl::class.java
                )
            )
        }

//        thread.start();
        try {
            LogcatRunner.getInstance()
                .config(
                    LogcatRunner.LogConfig.builder()
                        .setWsCanReceiveMsg(true)
                        .write2File(true)
                )
                .with(applicationContext)
                .start()
        } catch (e: IOException) {
            e.printStackTrace()
        }

//        Intent intent = new Intent(MainActivity.this, MyNotifiService.class);//启动服务
//        startForegroundService(intent);//启动服务
//        Intent intent_s = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
//        startActivity(intent_s);
//        checkNotificationPermission();
//        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
//        Iterator<String> iterator = packageNames.iterator();
//        while (iterator.hasNext()) {
//            Log.i("zrz", "=========" + iterator.next().toString());
//        }
//        testSet();
//
//        Set<String> enabledListenerPackages = NotificationManagerCompat.getEnabledListenerPackages(this);
//        Iterator<String> iterator1 = enabledListenerPackages.iterator();
//        while (iterator1.hasNext()) {
//            Log.i("zrz", "======11===" + iterator1.next().toString());
//        }
        threadHandle()
        findViewById<View>(R.id.ll_parent).setOnClickListener { Log.i("zrz", "parent") }
        findViewById<View>(R.id.btn_test).setOnClickListener { Log.i("zrz", "btn_test") }
        ipSetting()
        adbSetting()
        externalSdPath
    }

    private val externalSdPath: Unit
        private get() {
            val mStorageManager = getSystemService(STORAGE_SERVICE) as StorageManager
            //获取所有挂载的设备（内部sd卡、外部sd卡、挂载的U盘）
            val volumes = mStorageManager.storageVolumes
            try {
                val storageVolumeClazz = Class
                    .forName("android.os.storage.StorageVolume")
                //通过反射调用系统hide的方法
                val getPath = storageVolumeClazz.getMethod("getPath")
                val isRemovable = storageVolumeClazz.getMethod("isRemovable")
                for (i in volumes.indices) {
                    val storageVolume = volumes[i] //获取每个挂载的StorageVolume

                    //通过反射调用getPath、isRemovable
                    val storagePath = getPath.invoke(storageVolume) as String //获取路径
                    val isRemovableResult = isRemovable.invoke(storageVolume) as Boolean //是否可移除
                    val description = storageVolume.getDescription(this)
                    Log.d(
                        "jason", " i=" + i + " ,storagePath=" + storagePath
                                + " ,isRemovableResult=" + isRemovableResult + " ,description=" + description
                    )
                }
            } catch (e: Exception) {
                Log.d("jason", " e:$e")
            }
        }

    private fun adbSetting() {
        val btnAdbSwitch = findViewById<Button>(R.id.btn_adb_switch)
            ?: return
        btnAdbSwitch.setOnClickListener { v: View? ->
            val dmsg = dmsg()
            val pxml = dxml()
            if (isAdbOpend) {
                pxml.setText("/params/cmd", "stop adbd")
                btnAdbSwitch.text = "open adb"
            } else {
                pxml.setText("/params/cmd", "start adbd")
                btnAdbSwitch.text = "close adb"
            }
            isAdbOpend = !isAdbOpend
            dmsg.to("/upgrade/root/cmd", pxml.toString())
        }
    }

    private fun ipSetting() {
        if (resources.configuration.orientation == 2) {
            val etIp = findViewById<EditText>(R.id.et_ip)
            val etSubmask = findViewById<EditText>(R.id.et_submask)
            val etGateway = findViewById<EditText>(R.id.et_gateWay)
            val regexIp = "^(\\d{1,3}.){3}\\d{1,3}$"
            val tvEth0 = findViewById<TextView>(R.id.tv_eth0)
            val tvUsb0 = findViewById<TextView>(R.id.tv_usb0)
            tvEth0.postDelayed(object : Runnable {
                override fun run() {
                    println("===========")
                    val eth0 = utils.getLocalIp("eth0")
                    if (!TextUtils.isEmpty(eth0)) {
                        tvEth0.text = "楼宇网口IP：$eth0"
                    }
                    val usb0 = utils.getLocalIp("usb0")
                    if (!TextUtils.isEmpty(usb0)) {
                        tvUsb0.text = "住户网口IP：$usb0"
                    }
                    tvEth0.postDelayed(this, 2000)
                }
            }, 1500)
            findViewById<View>(R.id.btn_commit).setOnClickListener { view: View? ->
                val strIp = etIp.text.toString()
                val ipMatches = Pattern.matches(regexIp, strIp)
                if (!ipMatches) {
                    Toast.makeText(this@MainActivity, "error ip input", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                val strSubMask = etSubmask.text.toString()
                val subMaskMatches = Pattern.matches(regexIp, strSubMask)
                if (!subMaskMatches) {
                    Toast.makeText(this@MainActivity, "error subMask input", Toast.LENGTH_SHORT)
                        .show()
                    return@setOnClickListener
                }
                val strGateWay = etGateway.text.toString()
                val gateWayMatches = Pattern.matches(regexIp, strGateWay)
                if (!gateWayMatches) {
                    Toast.makeText(this@MainActivity, "error gateWay input", Toast.LENGTH_SHORT)
                        .show()
                    return@setOnClickListener
                }
                val dmsg = dmsg()
                val dxml = dxml()
                dxml.setText("/params/ip", strIp)
                dxml.setText("/params/mask", strSubMask)
                dxml.setText("/params/gateway", strGateWay)
                dmsg.to("/control/net/usb0", dxml.toString())
            }
        }
        val sm = getSystemService(STORAGE_SERVICE) as StorageManager
        val storageVolumes = sm.storageVolumes
        for (i in storageVolumes.indices) {
            val storageVolume = storageVolumes[i]
            storageVolume.state
            storageVolume.getDescription(this)
            storageVolume.toString()
            Log.i(
                "zrz", """
     state=${storageVolume.state}/des=$storageVolume
     
     """.trimIndent()
            )
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.i("zrz", "config=" + newConfig.orientation)
    }

    private fun threadHandle() {
        Thread {
            Looper.prepare()
            subHandle = object : Handler() {
                override fun handleMessage(msg: Message) {
                    super.handleMessage(msg)
                    try {
                        Thread.sleep(20000)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    println("zzzzzzzzzz" + msg.what)
                }
            }
            Looper.loop()
        }.start()
    }

    override fun onResume() {
        super.onResume()
        //        setNavigationBarVisibility(this, false);
//        onCheckGooglePlayServices();
        curNetworkInfo
    }

    /**
     * 检查 Google Play 服务
     */
    private fun onCheckGooglePlayServices() {
        // 验证是否已在此设备上安装并启用Google Play服务，以及此设备上安装的旧版本是否为此客户端所需的版本
        val code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)
        Log.i("zrz", "code=$code")
        if (code == ConnectionResult.SUCCESS) {
            // 支持Google服务
        } else {
            /**
             * 依靠 Play 服务 SDK 运行的应用在访问 Google Play 服务功能之前，应始终检查设备是否拥有兼容的 Google Play 服务 APK。
             * 我们建议您在以下两个位置进行检查：主 Activity 的 onCreate() 方法中，及其 onResume() 方法中。
             * onCreate() 中的检查可确保该应用在检查成功之前无法使用。
             * onResume() 中的检查可确保当用户通过一些其他方式返回正在运行的应用（比如通过返回按钮）时，检查仍将继续进行。
             * 如果设备没有兼容的 Google Play 服务版本，您的应用可以调用以下方法，以便让用户从 Play 商店下载 Google Play 服务。
             * 它将尝试在此设备上提供Google Play服务。如果Play服务已经可用，则Task可以立即完成返回。
             */
            GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this)

            // 或者使用以下代码
            /**
             * 通过isUserResolvableError来确定是否可以通过用户操作解决错误
             */
            if (GoogleApiAvailability.getInstance().isUserResolvableError(code)) {
                /**
                 * 返回一个对话框，用于解决提供的errorCode。
                 * @param activity  用于创建对话框的父活动
                 * @param code      通过调用返回的错误代码
                 * @param activity  调用startActivityForResult时给出的requestCode
                 */
                GoogleApiAvailability.getInstance().getErrorDialog(this, code, 200).show()
            }
        }
    }

    //先关闭再启动
    fun toggleNotificationListenerService(context: Context) {
        val pm = context.packageManager
        pm.setComponentEnabledSetting(
            ComponentName(context, MyNotifiService::class.java),
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP
        )
        pm.setComponentEnabledSetting(
            ComponentName(context, MyNotifiService::class.java),
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP
        )
    }

    object State {
        var CONNECTED = 0
    }

    override fun onBackPressed() {
        super.onBackPressed()
    }

    private val curNetworkInfo: NetworkInfo?
        private get() {
            val connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
            val info = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            Log.d("zrzTest", "info.isAvailable(): " + info.isAvailable)
            Log.d("zrzTest", "info.isConnected(): " + info.isConnected)
            Log.d("zrzTest", "info.isConnectedOrConnecting(): " + info.isConnectedOrConnecting)
            Log.d("zrzTest", "info.isFailover(): " + info.isFailover)
            Log.d("zrzTest", "info.isRoaming(): " + info.isRoaming)
            return null
        }

    private fun showNotification() {
        val intent = Intent(this, MainActivity::class.java)
        intent.flags =
            Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
        val channelId = createNotificationChannel(
            "my_channel_ID",
            "my_channel_NAME",
            NotificationManager.IMPORTANCE_HIGH
        )
        val notification = NotificationCompat.Builder(this, channelId!!)
            .setContentTitle("通知")
            .setContentText("收到一条消息")
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
        val notificationManager = NotificationManagerCompat.from(this)
        notificationManager.notify(100, notification.build())
    }

    private fun createNotificationChannel(
        channelID: String,
        channelNAME: String,
        level: Int
    ): String? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager =
                getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channel = NotificationChannel(channelID, channelNAME, level)
            manager.createNotificationChannel(channel)
            channelID
        } else {
            null
        }
    }

    private fun addFloatView() {
        val wm = this.application.getSystemService(WINDOW_SERVICE) as WindowManager
        val p = WindowManager.LayoutParams()
        p.type = WindowManager.LayoutParams.TYPE_PHONE
        p.format = PixelFormat.RGBA_8888
        p.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
        p.x = 0
        p.y = 0
        p.width = View.MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.EXACTLY)
        p.height = View.MeasureSpec.makeMeasureSpec(160, View.MeasureSpec.EXACTLY)
        p.gravity = Gravity.CENTER or Gravity.BOTTOM
        val inflater = LayoutInflater.from(this.application)
        val floatView: View = inflater.inflate(R.layout.float_item, null) as RelativeLayout
        floatView.findViewById<View>(R.id.btn_landscape).setOnClickListener { v: View? ->
            val dmsg = dmsg()
            val pxml = dxml()
            pxml.setText("/params/cmd", "settings put system accelerometer_rotation 0")
            dmsg.to("/upgrade/root/cmd", pxml.toString())
            pxml.setText("/params/cmd", "settings put system user_rotation 0")
            dmsg.to("/upgrade/root/cmd", pxml.toString())
            (getSystemService("window") as WindowManager).addView(
                 View (this),
                CustomLayout (0)
            );
            Settings.System.putInt(getContentResolver(), "accelerometer_rotation", 0);

        }
        floatView.findViewById<View>(R.id.btn_portrait).setOnClickListener { v: View? ->
            val dmsg = dmsg()
            val pxml = dxml()
            pxml.setText("/params/cmd", "settings put system accelerometer_rotation 0")
            dmsg.to("/upgrade/root/cmd", pxml.toString())
            pxml.setText("/params/cmd", "settings put system user_rotation 1")
            dmsg.to("/upgrade/root/cmd", pxml.toString())
            (getSystemService("window") as WindowManager).addView(
                View (this),
                CustomLayout (2)
            );
        }
        wm.addView(floatView, p)
    }

    private fun recoveryMode() {
        val ACTION_MASTER_CLEAR = "android.intent.action.MASTER_CLEAR"
        val EXTRA_REASON = "android.intent.extra.REASON"
        val FLAG_RECEIVER_FOREGROUND = 268435456
        val intent = Intent(ACTION_MASTER_CLEAR)
        intent.addFlags(FLAG_RECEIVER_FOREGROUND)
        intent.putExtra(EXTRA_REASON, "MasterClearConfirm")
        sendBroadcast(intent)
        finish()
    }


    class CustomLayout(paramInt: Int) :
        WindowManager.LayoutParams(0, 0, 2005, 8, -3) {
        init {
            gravity = 48
            screenOrientation = paramInt
        }
    }
    /**
     * 数据库测试
     */
    fun insert() {
        val table_0 = Table(32434, "语文", "张三", "109")
        val table_1 = Table(324345, "英语", "李四", "234")
        val table_2 = Table(3243456, "数学", "王五", "123")
        dbEngine!!.inserTable(table_0, table_1, table_2)
    }

    /**
     * 数据库测试
     */
    fun query() {
        dbEngine!!.queryAllTable()
    }

    companion object {
        private val mHandler: Handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                println("zzzzzzzzzz" + msg.what)
            }
        }
        private val thread = Thread {
            try {
                Thread.sleep(5000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            mHandler.sendEmptyMessage(1)
        }

        fun setNavigationBarVisibility(activity: Activity, isVisibility: Boolean) {
            if (Build.VERSION.SDK_INT < 19) {
                val v = activity.window.decorView
                v.systemUiVisibility = if (isVisibility) View.VISIBLE else View.GONE
            } else {
                val decorView = activity.window.decorView
                val hideUiOptions =
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
                val showUiOptions = View.SYSTEM_UI_FLAG_VISIBLE
                decorView.systemUiVisibility = if (isVisibility) showUiOptions else hideUiOptions
            }
        }
    }
}